//
//  ViewController.m
//  Compass
//
//  Created by yeshaojian on 16/5/28.
//  Copyright © 2016年 yeshaojian. All rights reserved.
//

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController () <CLLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *comPassImage;
@property (nonatomic, strong) CLLocationManager *locM;

@end

@implementation ViewController

- (CLLocationManager *)locM
{
    if (!_locM) {
        _locM = [[CLLocationManager alloc] init];
        
        _locM.delegate = self;
    }
    return _locM;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 判断当前设备磁力计是否正常
    if (![CLLocationManager headingAvailable]) {
        return;
    }
    
    [self.locM startUpdatingHeading];
}

#pragma mark - CLLocationManagerDelegate

// 接收到设备朝向
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
    // 判断朝向是否有效
    if (newHeading.headingAccuracy < 0) {
        return;
    }
    
    // 获取设备朝向
    CLLocationDirection angle = newHeading.magneticHeading;
    
    // 将角度转成弧度（角度 / 180.0 * M_PI）
    CGFloat hudu = angle / 180.0 * M_PI;
    
    // 因为如果没有动画的话旋转的时候回出现卡顿的现象，为了更流畅，我们给它加个动画
    [UIView animateWithDuration:0.1 animations:^{
        // 旋转图片
        self.comPassImage.transform = CGAffineTransformMakeRotation(-hudu);
    }];
    
}

@end
